package mv.releaser.controler;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

import javax.swing.DefaultComboBoxModel;
import javax.swing.LookAndFeel;
import javax.swing.UIManager;

import mv.releaser.model.MvReleaser;
import mv.releaser.view.MainWindowJFormD;

public class SaveConfiguration {
	private ConfigObject		config;
	private MainWindowJFormD	view;
	private MvReleaser			mvReleaser;

	public SaveConfiguration(ConfigObject config, MvReleaser mvReleaser,
			MainWindowJFormD view) {
		super();
		this.config = config;
		this.view = view;
		this.mvReleaser = mvReleaser;

		modifyConfig();
		writeConfig();

	}

	private void writeConfig() {
		try {
			// ouverture d'un flux de sortie vers le fichier "personne.serial"
			FileOutputStream fos = new FileOutputStream("config.data");

			// création d'un "flux objet" avec le flux fichier
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			try {
				// sérialisation : écriture de l'objet dans le flux de sortie
				oos.writeObject(config);
				// on vide le tampon
				oos.flush();
				System.out.println(config + " a ete serialise");
			} finally {
				// fermeture des flux
				try {
					oos.close();
				} finally {
					fos.close();
				}
			}
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}

	private void modifyConfig() {
		if (config == null)
			config = new ConfigObject();

		DefaultComboBoxModel genreModel = view.getGenreModel();
		DefaultComboBoxModel typeModel = view.getTypeModel();
		DefaultComboBoxModel audioModel = view.getAudioModel();
		DefaultComboBoxModel sourceModel = view.getSourceModel();
		DefaultComboBoxModel languageModel = view.getLanguageModel();
		DefaultComboBoxModel deinterlaceModel = view.getDeinterlaceModel();
		DefaultComboBoxModel formatModel = view.getFormatModel();
		DefaultComboBoxModel ripperModel = view.getRipperModel();
		DefaultComboBoxModel groupModel = view.getGroupModel();
		String lastSavePath = mvReleaser.getLastSavePath();
		String lastOpenPath = mvReleaser.getLastOpenPath();
		String laf = UIManager.getLookAndFeel().getClass().getName();
		System.out.println("laf = " + laf);
		config.setGenreModel(genreModel);
		config.setTypeModel(typeModel);
		config.setAudioModel(audioModel);
		config.setSourceModel(sourceModel);
		config.setLanguageModel(languageModel);
		config.setDeinterlaceModel(deinterlaceModel);
		config.setFormatModel(formatModel);
		config.setRipperModel(ripperModel);
		config.setGroupModel(groupModel);
		config.setLastSavePath(lastSavePath);
		config.setLastOpenPath(lastOpenPath);
		config.setLookAndFeel(laf);
	}

}
